package com.example.aicooking.service.imp;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.aicooking.entity.DifyMessageRequest;
import com.example.aicooking.entity.DifyProperties;
import com.example.aicooking.entity.dto.ChatHistoryResponse;
import com.example.aicooking.service.DifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.util.UriComponentsBuilder;

@Service
@Slf4j
public class DifyServiceImpl implements DifyService {

    @Autowired
    private DifyProperties difyProperties;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final Map<String, String> userConversations = new ConcurrentHashMap<>();

    public DifyServiceImpl() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public ResponseEntity<String> sendMessage(String message, String userId, String appId) {
        // 获取指定的应用配置
        DifyProperties.Application app = difyProperties.getApplications().get(appId);
        if (app == null) {
            return ResponseEntity.badRequest().body("未找到指定的AI应用");
        }

        try {
            String conversationId = userConversations.get(userId);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(app.getKey());  // 使用指定应用的API key
            headers.setAccept(Collections.singletonList(MediaType.TEXT_EVENT_STREAM));

            DifyMessageRequest request = new DifyMessageRequest(message, conversationId, userId);
            log.info("发送请求到Dify: {}", request);

            HttpEntity<DifyMessageRequest> entity = new HttpEntity<>(request, headers);
            String url = difyProperties.getUrl() + "/v1/chat-messages";
            log.info("请求URL: {}", url);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    String.class
            );

            log.info("Dify API 响应状态码: {}", response.getStatusCode());
            log.info("Dify API 响应内容: {}", response.getBody());

            if (response.getStatusCode() != HttpStatus.OK) {
                log.error("请求失败: {}", response.getStatusCode());
                return ResponseEntity.status(response.getStatusCode()).body("请求失败");
            }

            // 处理响应
            StringBuilder messageBuilder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new StringReader(response.getBody()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.debug("读取到响应行: {}", line);
                if (line.startsWith("data: ")) {
                    String jsonStr = line.substring(6);
                    log.debug("解析JSON: {}", jsonStr);
                    JsonNode jsonNode = objectMapper.readTree(jsonStr);

                    // 处理消息内容
                    if (jsonNode.has("message")) {
                        messageBuilder.append(jsonNode.get("message").asText());
                    } else if (jsonNode.has("answer")) {
                        messageBuilder.append(jsonNode.get("answer").asText());
                    } else if (jsonNode.has("text")) {
                        messageBuilder.append(jsonNode.get("text").asText());
                    }

                    // 更新会话ID
                    if (jsonNode.has("conversation_id")) {
                        String newConversationId = jsonNode.get("conversation_id").asText();
                        userConversations.put(userId, newConversationId);
                        log.info("更新会话ID: {}", newConversationId);
                    }
                }
            }

            String finalMessage = messageBuilder.toString();
            if (!StringUtils.isEmpty(finalMessage)) {
                log.info("成功获取到AI响应: {}", finalMessage);
                return ResponseEntity.ok(finalMessage);
            } else {
                log.warn("未获取到有效响应内容");
                return ResponseEntity.ok("未获取到有效响应");
            }

        } catch (Exception e) {
            log.error("Dify API 调用失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("AI对话服务暂时不可用: " + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<ChatHistoryResponse> getMessageHistory(String userId, String conversationId,
                                                                 String firstId, Integer limit, String appId) {
        // 获取指定的应用配置
        DifyProperties.Application app = difyProperties.getApplications().get(appId);
        if (app == null) {
            throw new RuntimeException("未找到指定的AI应用");
        }

        try {
            String url = difyProperties.getUrl() + "/v1/messages";

            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                    .queryParam("user", userId)
                    .queryParam("conversation_id", conversationId);

            log.info("请求URL: {}", builder.toUriString());

            if (firstId != null) {
                builder.queryParam("first_id", firstId);
            }
            if (limit != null) {
                builder.queryParam("limit", limit);
            }

            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + app.getKey());
            headers.setContentType(MediaType.APPLICATION_JSON);

            try {
                ResponseEntity<ChatHistoryResponse> response = restTemplate.exchange(
                        builder.toUriString(),
                        HttpMethod.GET,
                        new HttpEntity<>(headers),
                        ChatHistoryResponse.class
                );
                return response;
            } catch (HttpClientErrorException.NotFound e) {
                log.warn("会话不存在 - conversationId: {}, userId: {}", conversationId, userId);
                ChatHistoryResponse emptyResponse = new ChatHistoryResponse();
                emptyResponse.setLimit(limit != null ? limit : 20);
                emptyResponse.setHasMore(false);
                emptyResponse.setData(new ArrayList<>());
                return ResponseEntity.ok(emptyResponse);
            }
        } catch (Exception e) {
            log.error("获取历史消息失败: {}", e.getMessage());
            throw new RuntimeException("获取历史消息失败: " + e.getMessage());
        }
    }
}